<?php
namespace app\bancard\controller;

use app\bancard\model\ExaminationMode;
use think\Collection;
use think\Db;
use think\Exception;
use think\facade\Cache;
use app\common\validate\ExamValidate;
use app\common\validate\ExaminationSubjectValidate;
use app\bancard\model\ExaminationMode as ExamModel;
use app\bancard\model\ExaminationRoom;
use app\bancard\model\ExaminationSubject;

class Exam extends Common
{
    
    //首页
    public function index()
    {
        return $this->fetch();
    }
    
	public function subjectList(){
		$count = 10;
		$result = [
			[
				'id'=>1,
				'room_name'=>"101",
				'start_number'=>1,
				'end_number'=>100,
				'data'=>[
					[
						'name'=>"语文",
						'time' =>"9:40-11:40",
						'teacher'=>"王小玉"
					],
					[
						'name'=>"数学",
						'time' =>"9:40-11:40",
						'teacher'=>"王小玉"
					]
				]
				
			],
			[
				'id'=>2,
				'room_name'=>"102",
				'start_number'=>1,
				'end_number'=>100,
				'data'=>[
					[
						'name'=>"语文",
						'time' =>"9:40-11:40",
						'teacher'=>"王小玉"
					],
					[
						'name'=>"数学",
						'time' =>"9:40-11:40",
						'teacher'=>"王小玉"
					]
				]
				
			]
		];
		
		return showTable(0, 'OK', $count, $result, 200);
	}
	
    public function lists()
    {
        $user_id = session('admin.id');
        $school_id = session('schoolInfo.id');
        $ntitle =request()->param('keywords');
        $title = isset($ntitle)?$ntitle:'';
        $limit = request()->param('limit');
        $offset = request()->param('offset');
        $start = ($offset-1)*$limit;
        $map =[
            'user_id'=>$user_id,
            'school_id'=>$school_id
        ];
        if ($title) {
            $count = db('examination_mode')->where($map)->whereLike('exam_name', "%$title%")->count();
            $result = db('examination_mode')->where($map)->whereLike('exam_name', "%$title%")->limit($start, $limit)->order('id desc,sort desc')->select();
        } else {
            $count = db('examination_mode')->where($map)->count();
            $result = db('examination_mode')->where($map)->limit($start, $limit)->order('id desc,sort desc')->select();
        }
        return showTable(0, 'OK', $count, $result, 200);
    }
    
    
    public function roomlists()
    {
        
        return $this->fetch();
    }
	
	public function roomdata(){
		$id = request()->param('id');
		$limit = request()->param('limit');
		$page = request()->param('page');
		$start = ($page-1)*$limit;
		$count = db('examination_room')->where(['mode_id'=>$id])->count();
		$result = db('examination_room')->where(['mode_id'=>$id])->limit($start, $limit)->order('id desc')->select();
		$room_ids = implode(',', array_unique(array_column($result, 'room_id')));

		$roomName = $this->getRoomRelation($room_ids);
//        p($roomName);die;
		foreach ($result as $key => $value) {
		    if (isset($roomName[$value['room_id']])) {
		        $result[$key]['room_name'] = $roomName[$value['room_id']]['name'];
		    }
		}
		return showTable(0, 'OK', $count, $result, 200);
	}
    
	public function subject(){
		$id = request()->param('id');
		$limit = request()->param('limit');
		$page = request()->param('page');
		$start = ($page-1)*$limit;
		$count = db('examination_subject')->where(['r_id'=>$id])->count();
		$result = db('examination_subject')->where(['r_id'=>$id])->limit($start, $limit)->order('id desc')->select();
		return showTable(0, 'OK', $count, $result, 200);
	}
	
    //查看
    public function view()
    {
        $data = request()->param();
        $result = db('examination_mode')->where('id', $data['id'])->find();
        $this->assign('result', $result);
        return $this->fetch();
    }
    //编辑
    public function edit()
    {
        if (request()->isPost()) {
            $data = request()->param();
            $data['user_id'] = session('admin.id');
            $data['school_id'] = session('schoolInfo.id');
            $data['platform'] = 1;
            $data['class_ids'] =  implode(",", $data['class_ids']);
            $data['update_time'] = date('Y-m-d H:i:s', time());
            $validate = new ExamValidate;
            if (!$validate->scene('edit')->check($data)) {
                return show(0, $validate->getError(), 0, 200);
            } else {
                Cache::clear('examination_mode');
                $rest = (new ExamModel())->strict(false)->where('id', $data['id'])->update($data);
                return show(1, '修改成功', $rest, 200);
            }
        }
        $data = request()->param();
        $result = db('examination_mode')->where('id', '=', $data['id'])->find();
        $egetClass = $this->egetClass($result['class_ids']);
        $this->assign('egetClass', json_encode($egetClass['data']));
        $this->assign('result', $result);
        return $this->fetch();
    }
    //添加
    public function add()
    {
        if (request()->isPost()) {

            $data = request()->param();
            $data['user_id'] = session('admin.id');
            $data['school_id'] = session('schoolInfo.id');
			$data['number_start'] = $data['number_start'] * 1;
			$data['number_end'] = $data['number_end'] * 1;


			$class_count = count($data['class_ids']) * $data['number_pre_class'];//教室座位数
			$need_count = $data['number_end'] - $data['number_start']; //考试人数
			
			if($need_count < 0) {
                // 考试人数不对
                return show(0, '考试人数不合适', "", 200);
			}
			if ($need_count > $class_count) {
                // 坐不下
                return show(0, '座位设置太少人数太对坐不下', "", 200);
			}
			$examModel = new ExamModel();
			Db::transaction(function() use ($data,$examModel) {
				
				$examModel->save([
					'exam_name' => $data['title'],
                    'start_time' => strtotime($data['start_date']),
                    'end_time' => strtotime($data['end_date']),
					'number_start' => $data['number_start'],
					'number_end' => $data['number_end'],
					'number_pre_class' => $data['number_pre_class'],
					'user_id' => $data['user_id'],
					'school_id' => $data['school_id'],
                    'update_time' =>date('Y-m-d H:i:s', time())
				]);
				
				$examination_room = [];
				$number = $data['number_start'];
				foreach($data['class_ids'] as $val) {
					$examination_room[] = [
						'mode_id' => $examModel->id,
						'room_id' =>  $val,
						'class_id' =>  $val,
						'number_start' => $number,
						'number_end' => $number + $data['number_pre_class'],
					];
					$number += $data['number_pre_class'];
				}
				$ExaminationRoom = new ExaminationRoom();
				$rooms = $ExaminationRoom->saveAll($examination_room);
				$subject_data = array_map(function ($name, $start_time, $end_time) {
					return [
						'subject_name' => $name,						
						'start_time' => strtotime($start_time),
						'end_time' => strtotime($end_time),
					];
				}, $data['subject']['name'], $data['subject']['start_time'], $data['subject']['end_time']);
				
				$insert_subject_data = [];
				foreach($rooms as $key=>$room) {
					foreach($subject_data as $k=>$subject) {
						$insert_subject_data[] = array_merge($subject, ['r_id' => $room->id]);
					}
				}

				$ExaminationSubject = new ExaminationSubject();
				//p($insert_subject_data);die;
				$ExaminationSubject->saveAll($insert_subject_data);
				
				
			});
			$data['exam_id'] = $examModel->id;
            $pushKey = [
                'action' => 'exam'
            ];
            $this->socketPush($data['class_ids'],$pushKey);
			return show(1, '添加成功', $data, 200);
        }
        $egetClass = $this->getClass();
        $this->assign('egetClass', json_encode($egetClass['data']));
        return $this->fetch();
    }
	public function step()
	{
		return $this->fetch();
	}
    //批量删除
    public function delete()
    {
        Cache::clear('examination_mode');
        $data = request()->param();

        $exam_mode = db('examination_mode')
            ->alias('a')
            ->leftJoin('examination_room b','a.id=b.mode_id')
            ->whereIn('a.id',$data['ids'])
            ->select();


        $class_ids = array_unique(array_column($exam_mode,'class_id'));
        $mode_ids = array_unique(array_column($exam_mode,'mode_id'));

        $rooms = ExaminationRoom::whereIn('mode_id', $mode_ids)->field('id,mode_id')->select();

        $room_ids = array_column($rooms->toArray(), 'id');

        Db::startTrans();
        try {

            ExaminationSubject::whereIn('r_id', $room_ids)->delete();
            ExaminationRoom::whereIn('mode_id', $mode_ids)->delete();
            ExaminationMode::where('id', $data['ids'])->delete();

            $result = 1;
            Db::commit();

        } catch (Exception $e) {
            $result = 0;
            $msg = $e->getMessage();
            Db::rollback();
        }



        $this->socketPush($class_ids,[
            'action' => 'exam'
        ]);

        return show(1, '删除成功', $result, 200);
    }
    //是否显示
    public function show()
    {
        $data = request()->param();
        Cache::clear('examination_mode');
        $result = db('examination_mode')->where('id', $data['id'])->update(['show'=>$data['status']]);
        return show(1, '设置成功', $result, 200);
    }
    //是否置顶
    public function top()
    {
        $data = request()->param();
        Cache::clear('examination_mode');
        $result = db('examination_mode')->where('id', $data['id'])->update(['istop'=>$data['status']]);
        return show(1, '设置成功', $result, 200);
    }
    //排序
    public function sort()
    {
        $data = request()->param();
        
        $validate = new ExamValidate;
        
        if (!$validate->scene('sort')->check($data)) {
            return show(config('code.error'), 'error', $validate->getError(), 200);
        } else {
            Cache::clear('examination_mode');
            $rest = (new ExamModel())->save(['sort'=>$data['sort']], ['id'=>$data['id']]);
            return show(config('code.success'), 'OK', $rest, 200);
        }
    }
	//添加和编辑监考老师
	public function edit_sub_name(){
		$data = request()->param();
		
		$validate = new ExaminationSubjectValidate;
		
		if (!$validate->scene('add')->check($data)) {
		    return show(config('code.error'), 'error', $validate->getError(), 200);
		} else {
		    Cache::clear('examination_subject');
		    $rest = (new ExaminationSubject())->save(['teacher_name'=>$data['teacher_name']], ['id'=>$data['id']]);
		    return show(config('code.success'), 'OK', $rest, 200);
		}
	}
}
